package com.lancoo.tyjx.multichatroom.adapter;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Vibrator;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lancoo.tyjx.multichatroom.R;
import com.lancoo.tyjx.multichatroom.activity.MyApplication;
import com.lancoo.tyjx.multichatroom.activity.ShowPicActivitiy;
import com.lancoo.tyjx.multichatroom.activity.ShowPicFragment;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.expression.ExpressionUtil;
import com.lancoo.tyjx.multichatroom.gifView.GifView;
import com.lancoo.tyjx.multichatroom.gifView.GifView.GifImageType;
import com.lancoo.tyjx.multichatroom.image.ImgConfig;
import com.lancoo.tyjx.multichatroom.image.ImgHandler;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.utils.CircleTransform;
import com.lancoo.tyjx.multichatroom.utils.DateUtil;
import com.lancoo.tyjx.multichatroom.utils.FileUtil;
import com.lancoo.tyjx.multichatroom.utils.ImageUtil;
import com.lancoo.tyjx.multichatroom.utils.MyTimeCountDown;
import com.lancoo.tyjx.multichatroom.utils.StringUtil;
import com.lancoo.tyjx.multichatroom.utils.Tool;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

public class ChatAdapter extends BaseAdapter {
    private Context cxt;
    private static int[] resTo = {R.drawable.voiceto0, R.drawable.voiceto1,
            R.drawable.voiceto2, R.drawable.voiceto3};
    private static int[] resFrom = {R.drawable.voicefrom0,
            R.drawable.voicefrom1, R.drawable.voicefrom2, R.drawable.voicefrom3};
    private String username = null;
    private FragmentManager fragmentManager;
    private Bitmap bitmap;
    private List<ChatItem> chatItems;
    private static final String TAG = "ChatAdapter";

    private OnFileClickListener onFileClickListener = null;
    private OnAudioPlayListener onAudioPlayListener = null;

    public interface OnAudioPlayListener {
        void prepare();

        void complete();
    }

    public ChatAdapter(Context context, String username, FragmentManager fragmentManager, OnAudioPlayListener onAudioPlayListener, OnFileClickListener onFileClickListener) {
        this.cxt = context;
        this.username = username;
        this.fragmentManager = fragmentManager;
        this.onAudioPlayListener = onAudioPlayListener;
        this.onFileClickListener = onFileClickListener;
    }


    public interface MsgType {
        int MSG_OUT = 0;
        int MSG_IN = 1;
    }

    public ChatAdapter(Context context, String username, OnFileClickListener onFileClickListener) {
//		super(context, 0);
        this.cxt = context;
        this.username = username;
        this.onFileClickListener = onFileClickListener;
    }

    public void initDataSource(List<ChatItem> chatItems) {
        this.chatItems = chatItems;
    }

    @Override
    public int getItemViewType(int position) {
        ChatItem nowMsg = chatItems.get(position);
        if (nowMsg.inOrOut == 1) {
            return MsgType.MSG_OUT;
        } else {
            return MsgType.MSG_IN;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return chatItems.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return chatItems.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ChatItem item = chatItems.get(position);
        final ViewHolder viewHolder;
        int msgType = getItemViewType(position);
        if (convertView == null) {
            if (msgType == MsgType.MSG_OUT) {
                convertView = LayoutInflater.from(cxt).inflate(
                        R.layout.row_chat_mine, null);
            } else {
                convertView = LayoutInflater.from(cxt).inflate(
                        R.layout.row_chat, null);
            }
            viewHolder = new ViewHolder();
            viewHolder.timeView = (TextView) convertView
                    .findViewById(R.id.timeView);
            viewHolder.msgView = (TextView) convertView
                    .findViewById(R.id.msgView);
            viewHolder.head = (ImageView) convertView
                    .findViewById(R.id.headImg);
            viewHolder.img = (ImageView) convertView.findViewById(R.id.imgView);
            viewHolder.gifImg = (ImageView) convertView
                    .findViewById(R.id.gifImgView);
            viewHolder.voice = (ImageView) convertView
                    .findViewById(R.id.voiceView);
            viewHolder.llFileView = (LinearLayout) convertView.findViewById(R.id.ll_file_view);
            viewHolder.ivfile = (ImageView) convertView.findViewById(R.id.iv_file);
            viewHolder.tvfileName = (TextView) convertView.findViewById(R.id.tv_file_name);
            viewHolder.soundDuration = (TextView) convertView
                    .findViewById(R.id.soundView);
            viewHolder.gif = (GifView) convertView.findViewById(R.id.gifView);
            viewHolder.nameView = (TextView) convertView
                    .findViewById(R.id.nameView);
            viewHolder.sendStateView = (GifView) convertView.findViewById(R.id.sendstateView);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            viewHolder.timeView.setVisibility(View.VISIBLE);
            viewHolder.msgView.setVisibility(View.VISIBLE);
            viewHolder.head.setVisibility(View.VISIBLE);
            viewHolder.img.setVisibility(View.GONE);
            viewHolder.gifImg.setVisibility(View.GONE);
            viewHolder.voice.setVisibility(View.GONE);
            viewHolder.soundDuration.setVisibility(View.GONE);
            viewHolder.gif.setVisibility(View.GONE);
            viewHolder.llFileView.setVisibility(View.GONE);
            viewHolder.ivfile.setVisibility(View.GONE);
            viewHolder.tvfileName.setVisibility(View.GONE);
            viewHolder.nameView.setVisibility(View.GONE);
            if (item.inOrOut == 1) {
                viewHolder.sendStateView.setVisibility(View.GONE);
            }
        }

        if (item.inOrOut == 1) {
            if (item.sendState == 0) {//正在发送
                viewHolder.sendStateView.setVisibility(View.VISIBLE);
                viewHolder.sendStateView.setImageResource(R.drawable.message_send_now);
                viewHolder.sendStateView.setGifImageType(GifImageType.COVER);
                viewHolder.sendStateView.setGifImage(R.drawable.message_send_now);
            } else if (item.sendState == 1) {//发送成功
                viewHolder.sendStateView.setVisibility(View.GONE);
            } else if (item.sendState == 2) {//发送失败
                viewHolder.sendStateView.setVisibility(View.VISIBLE);
                viewHolder.sendStateView.setGifImageType(GifImageType.COVER);
                viewHolder.sendStateView.setGifImage(R.drawable.message_send_failed);
                viewHolder.sendStateView.setImageResource(R.drawable.message_send_failed);
            } else {
                viewHolder.sendStateView.setVisibility(View.GONE);
            }
        }

        // head 头像
//        if (item.inOrOut == 0) { // 接收
////            if (item.chatType == ChatItem.CHAT) {
////
////                if (bitmap == null) {
////                    viewHolder.head.setImageDrawable(ImgHandler
////                            .ToCircularBig(R.drawable.default_icon));
////                } else {
////                    viewHolder.head.setImageBitmap(bitmap);
////                }
////            } else {
////                ImgConfig.showHeadImg(item.username, viewHolder.head);
////            }
//
//            if (TextUtils.isEmpty(item.head)){
//                viewHolder.head.setImageDrawable(ImgHandler
//                           .ToCircularBig(R.drawable.default_icon));
//            }
//
//        } else {
//            ImgConfig.showHeadImg(Constants.USER_NAME, viewHolder.head);
//        }
        if (!TextUtils.isEmpty(item.head)) {
            Picasso.get().load(item.head).transform(new CircleTransform()).placeholder(R.drawable.default_icon).into(viewHolder.head);
        } else {
            if (item.inOrOut == 0) { // 接收
                if (item.chatType == ChatItem.CHAT) {
                    if (bitmap == null) {
                        viewHolder.head.setImageDrawable(ImgHandler
                                .ToCircularBig(R.drawable.default_icon));
                    } else {
                        viewHolder.head.setImageBitmap(bitmap);
                    }
                } else {
                    ImgConfig.showHeadImg(item.username, viewHolder.head);
                }
                if (TextUtils.isEmpty(item.head)) {
                    viewHolder.head.setImageDrawable(ImgHandler
                            .ToCircularBig(R.drawable.default_icon));
                }
            } else {
                ImgConfig.showHeadImg(Constants.USER_NAME, viewHolder.head);
            }
        }

        // 五分钟内则不显示相同时间了
        ChatItem lastMsg = null;
        if (position != 0) {
            lastMsg = (ChatItem) getItem(position - 1);
        }
        if ((lastMsg != null && DateUtil.isBetween5WithLast(lastMsg.sendDate, item.sendDate))
                || (lastMsg != null && DateUtil.isBetween5WithLast(lastMsg.sendDate, item.sendDate) && DateUtil.isInFiveMinute(item.sendDate))) {
            viewHolder.timeView.setVisibility(View.GONE);
        } else {
            viewHolder.timeView.setText(DateUtil.getRecentTimeMM_dd_ss(item.sendDate));
        }

        // text
        // 适配图片、声音等文件
        if (item.msg != null && item.msg.contains(Constants.PATH)) {
            String path = item.msg;
            File file = new File(path);
            if (file.exists() && file.length() != 0) { // isExist
                viewHolder.msgView.setVisibility(View.GONE);
                int type = FileUtil.getType(path);

                if (type == FileUtil.IMG) { // isImg
                    showImg(viewHolder.img, path);
                } else if (type == FileUtil.SOUND) { // isSound
                    playSound(path, viewHolder.soundDuration, viewHolder.voice,
                            item.inOrOut == 1, item.getVoicetime());
                }
            } else {
                viewHolder.msgView.setText("加载中...");
            }
        } else if (!TextUtils.isEmpty(item.getMsgType()) && item.getMsgType().equals("file")) {
            int type = FileUtil.getType(item.fileName);
            viewHolder.msgView.setVisibility(View.GONE);
            viewHolder.tvfileName.setVisibility(View.VISIBLE);
            viewHolder.llFileView.setVisibility(View.VISIBLE);
            viewHolder.tvfileName.setVisibility(View.VISIBLE);
            viewHolder.tvfileName.setText(Tool.decodeJson(item.fileName));
            setFileView(type, item.getFileName(), item.getFileUrl(), viewHolder.ivfile);
        } else if (item.msg != null && item.msg.contains("[/g0")) { // isGif
            playGif(viewHolder.gif, viewHolder.msgView, viewHolder.gifImg,
                    item.msg, position);
        } else if (item.msg != null && item.msg.contains("[")) { // 适配表情
            viewHolder.msgView.setText(ExpressionUtil.getEmotionContent(cxt, viewHolder.msgView,
                    item.msg));
        } else if (item.msg != null && item.msg.contains("[/a0")) { // 适配地图
            viewHolder.msgView.setVisibility(View.GONE);
            showMap(viewHolder.img, item.msg);
        }
        // 点赞
        else {
            if (item.msg != null && item.msg.contains("{点赞}")) {
                item.msg = "对本课堂[点赞]";
                viewHolder.msgView.setTextColor(Color.parseColor("#ff0000"));
            } else if (item.msg != null && item.msg.contains("{取消点赞}")) {
                item.msg = "对本课堂[取消点赞]";
                viewHolder.msgView.setTextColor(Color.parseColor("#00008B"));
            } else {
//                if (item.inOrOut == 0) {
//                    viewHolder.msgView.setTextColor(Color.parseColor("#000000"));
//                } else {
//                    viewHolder.msgView.setTextColor(Color.parseColor("#000000"));
//                }

            }
            viewHolder.msgView.setText(item.msg);
        }

        if (item.chatType == ChatItem.GROUP_CHAT && item.inOrOut == 0) {
            viewHolder.nameView.setVisibility(View.VISIBLE);
            viewHolder.nameView.setText(item.username);
        } else {
            viewHolder.nameView.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(Constants.USER_NAME) && Constants.USER_NAME.contains("&")) {
                String userName = null;
                try {
                    userName = Constants.USER_NAME.split("&")[2];
                } catch (Exception e) {
                    userName = Constants.USER_NAME.split("&")[1];
                    e.printStackTrace();
                }

                viewHolder.nameView.setText(userName);
            }
        }


        // 内容复制
        viewHolder.msgView.setOnLongClickListener(new OnLongClickListener() {
            @SuppressLint("NewApi")
            @Override
            public boolean onLongClick(View v) {
                TextView msgView = (TextView) v;
                ClipboardManager cm = (ClipboardManager) cxt
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本数据复制到剪贴板
                cm.setText(msgView.getText());
                Vibrator vib = (Vibrator) cxt
                        .getSystemService(Context.VIBRATOR_SERVICE); // 震动提醒
                vib.vibrate(100);
                Tool.initToast(cxt, "复制成功");
                return false;
            }
        });
        return convertView;
    }

    private void setFileView(int type, String fileName, final String fileUrl, ImageView fileView) {

        fileView.setVisibility(View.VISIBLE);
        if (type == FileUtil.MOVIE) {
            fileView.setImageResource(R.drawable.res_type_01);
        } else if (type == FileUtil.SOUND) {
            fileView.setImageResource(R.drawable.res_type_02);
        } else if (type == FileUtil.TXT) {
            fileView.setImageResource(R.drawable.res_type_03);
        } else if (type == FileUtil.IMG) {
            fileView.setImageResource(R.drawable.res_type_04);
        } else if (type == FileUtil.WEB) {
            fileView.setImageResource(R.drawable.res_type_05);
        } else if (type == FileUtil.DOC) {
            fileView.setImageResource(R.drawable.res_type_06);
        } else if (type == FileUtil.PPT) {
            fileView.setImageResource(R.drawable.res_type_07);
        } else if (type == FileUtil.PDF) {
            fileView.setImageResource(R.drawable.res_type_08);
        } else if (type == FileUtil.XLS) {
            fileView.setImageResource(R.drawable.res_type_09);
        }
        fileView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != onFileClickListener) {
                    onFileClickListener.onCLick(fileUrl);
                }
            }
        });
    }

    private void showImg(ImageView img, final String path) {
        img.setVisibility(View.VISIBLE);
        img.setImageBitmap(ImageUtil.createImageThumbnail(path, 200 * 200));
        img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.putExtra("picPath", path);
//                intent.setClass(cxt, ShowPicActivitiy.class);
//                cxt.startActivity(intent);

                ShowPicFragment showPicFragment = ShowPicFragment.getInstance(path);
                showPicFragment.show(fragmentManager, "ShowPicFragment");
            }
        });

        // //内容复制
        img.setOnLongClickListener(new OnLongClickListener() {
            @SuppressLint("NewApi")
            @Override
            public boolean onLongClick(View v) {
                // FileUtil.changeFile(path,
                // Constants.IMG_PATH+"/"+FileUtil.getFileName(path));
                Tool.initToast(cxt, "图片已保存至本地" + path);
                MyApplication.getInstance().sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
                                .parse("file://" + path)));
                return false;
            }
        });
    }

    private void showMap(ImageView img, String msg) {
        img.setVisibility(View.VISIBLE);
        img.setImageResource(R.drawable.map);
        String[] adrs = msg.split(",");
        final double lat = Double.valueOf(adrs[1]);
        final double lon = Double.valueOf(adrs[2]);

        img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Intent intent = new Intent();
                // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // intent.putExtra("lat", lat);
                // intent.putExtra("lon", lon);
                // intent.setClass(cxt, MapActivity.class);
                // cxt.startActivity(intent);
            }
        });
    }

    /**
     * play gif
     *
     * @param gif
     * @param msg
     */
    private void playGif(GifView gif, TextView msgView, ImageView img,
                         String msg, int position) {
        msgView.setVisibility(View.GONE);
        try {
            Field field = R.drawable.class.getDeclaredField(msg.substring(2,
                    msg.indexOf("]")));
            int resId = Integer.parseInt(field.get(null).toString());
            if (getCount() - 1 - position < 3) { // 只显示三个动态
                gif.setVisibility(View.VISIBLE);
                gif.setGifImageType(GifImageType.COVER);
                gif.setGifImage(resId);
            } else {
                img.setVisibility(View.VISIBLE);
                img.setBackgroundResource(resId);
            }
        } catch (NoSuchFieldException e) {
            msgView.setVisibility(View.VISIBLE);
            msgView.setText(ExpressionUtil.getText(cxt,
                    StringUtil.Unicode2GBK(msg)));
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * play voice
     *
     * @param file
     * @param soundDuration
     * @param voice
     * @param isOut
     */
    public MediaPlayer mediaPlayer = new MediaPlayer();

    private String curAudioFileName;

    /**
     * 播放声音
     *
     * @param file
     * @param soundDuration
     * @param voice
     * @param isOut
     * @param voicetime
     */
    private void playSound(final String file, TextView soundDuration,
                           final ImageView voice, final boolean isOut, final int voicetime) {

        voice.setVisibility(View.VISIBLE);
        soundDuration.setVisibility(View.VISIBLE);

        soundDuration.setText("" + voicetime + "\"");
        voice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                countDownTimer.cancel();
                if (mediaPlayer.isPlaying() && curAudioFileName.equals(file)) {
                    mediaPlayer.stop();
                } else {
                    curAudioFileName = file;
                    countDownTimer.isOut = isOut;
                    countDownTimer.voice = voice;
                    countDownTimer.setTime(voicetime * 1000 + 1000, 500);
                    try {
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(file);
                        mediaPlayer.prepare();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.start();
                    countDownTimer.start();
                }

                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        Log.w(TAG, "mediaPlayer: onCompletion");
                        if (null != onAudioPlayListener) {
                            onAudioPlayListener.complete();
                        }
                    }
                });

                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        Log.w(TAG, "mediaPlayer: onPrepared");
                        if (null != onAudioPlayListener) {
                            onAudioPlayListener.prepare();
                        }
                    }
                });
            }
        });
    }

    // 用于录制的时候关闭语音
    public void stopPlayer() {
        if (null != mediaPlayer) {
            countDownTimer.cancel();
            mediaPlayer.stop();
        }
    }

    MyTimeCountDown countDownTimer = new MyTimeCountDown(5, 500) {
        int i = 0;

        @Override
        public void onTick(long millisUntilFinished) {

            Log.i(TAG, "onTick: millisUntilFinished " + millisUntilFinished + "	i " + i);
            {
                if (isOut) {
                    voice.setImageResource(resTo[i]);
                } else {
                    voice.setImageResource(resFrom[i]);
                }
                i++;
                if (i > 3) {
                    i = 0;
                }
            }
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "onTick: onFinish ");
            i = 0;
            if (null == voice) {
                return;
            }
            if (isOut) {
                voice.setImageResource(resTo[0]);
            } else {
                voice.setImageResource(resFrom[0]);
            }
        }
    };

    class ViewHolder {
        TextView timeView, msgView, soundDuration, nameView, tvfileName;
        ImageView head, img, gifImg, voice, ivfile;
        LinearLayout llFileView;
        GifView gif;
        GifView sendStateView;
    }

    public interface OnFileClickListener {
        void onCLick(String fileUrl);
    }

}